using System;
using Ext;
using Ext.data;
using Ext.form;
using ScriptFX;

namespace PageScripts {
    public class CategoryDetailsForm : Ext.util.Observable {
        private Form _form;
        private LayoutDialog _dialog;
        private FormMode _mode;
        private Record _currentRecord;

        public CategoryDetailsForm() {
            addEvents(new Dictionary(
                "inserted", true,
                "updated", true
            ));
        }

        public void Show(FormMode mode, Element el, Record rec) {
            _mode = mode;
            if (Script.IsNullOrUndefined(_dialog)) Init();
            if (_dialog.isVisible()) _dialog.hide(null);

            string title = "";
            if (_mode == FormMode.Update) {
                if (!Script.IsNullOrUndefined(rec)) {
                    _form.loadRecord(rec);
                    _currentRecord = rec;
                    title = "Update Category";
                } else {
                    MessageBox.alert("Select a Category first ...", "please choose a category to update from the list.", null, null);
                    return;
                }
            } else {
                _currentRecord = null;
                _form.reset();
                title = "Add New Category";
            }

            _dialog.getLayout().findPanel("category-edit-layout").setTitle(title);
            _dialog.show(el);
            _dialog.focus();
        }

        private void Init() {
   	        Script.Eval("Ext.form.Field.prototype.msgTarget = 'side'");
	        Script.Eval("Ext.form.Field.prototype.focusClass = 'text-field-focus'");
            Script.Eval("Ext.form.Field.prototype.invalidClass = 'text-field-invalid'");

            TextField name = new TextField(new Dictionary(
                "fieldLabel", "Name",
                "name", "CategoryName",
                "allowBlank", false
            ));

            TextArea desc = new TextArea(new Dictionary(
                "fieldLabel", "Description",
                "name", "Description",
                "allowBlank", true
            ));

            _form = new Form(new Dictionary(
                "labelAlign", "left",
                "url", "DataHandler.aspx"
            ));
            _form.column(new Dictionary(
                "width", 425,
                "labelWidth", 120,
                "style", "margin-left:8px;margin-top:8px"
            ));
            _form.fieldset(new Dictionary("id", "categoryForm", "legend", "Category Details"), name, desc);
            _form.applyIfToFields(new Dictionary("width", 255));
            _form.render("category-edit-form");

            _dialog = new LayoutDialog("category-edit-dialog", new Dictionary(
                "modal", false,
                "autoTabs", true,
                "proxyDrag", true,
                "width", 470,
                "height", 250,
                "shadow", true,
                "center", new Dictionary("autoScroll", true)
            ));
            _dialog.addButton("Save", new AnonymousDelegate(SaveData), this);
            _dialog.addButton("Cancel", new AnonymousDelegate(delegate() { _dialog.hide(null); }), _dialog);
            _dialog.addKeyListener(27, new AnonymousDelegate(delegate() { _dialog.hide(null); }), _dialog);

            BorderLayout layout = _dialog.getLayout();
            layout.beginUpdate();
            layout.add("center", new ContentPanel("category-edit-layout", new Dictionary("title", "Insert Basket"), null));
            layout.endUpdate(false); 
        }

        private void SaveData() {
            if (_mode == FormMode.Insert) {
                InsertCategory();
            } else if (_mode == FormMode.Update) {
                UpdateCategory();
            }
        }

        private void UpdateCategory() {
            if (!_form.isValid()) {
                MessageBox.alert("Invalid Information", "<br />Please correct the invalid fields<br />", null, null);
                return;
            }
            _form.submit(new Dictionary(
                "waitMsg", "Creating New Category",
                "reset", false,
                "params", new Dictionary("action", "UpdateCategory", "CategoryID", _currentRecord.get("CategoryID")),
                "scope", this,
                "failure", new FormSubmitDelegate(delegate(Form form, Action action) {
                    MessageBox.alert("Error!", "There were errors saving this basket. <br />Please correct the errors and try again.", null, null);
                    fireEvent("updated", this, false, null);
                }),
                "success", new FormSubmitDelegate(delegate(Form form, Action action) {
                    _dialog.hide(null);
                    Dictionary newValues = new Dictionary(
                        "CategoryID", _currentRecord.get("CategoryID"),
                        "CategoryName", _form.findField("CategoryName").getValue(),
                        "Description", _form.findField("Description").getValue()
                    );
                    fireEvent("updated", this, true, newValues);
                })

            ));
        }

        private void InsertCategory() {
            if (!_form.isValid()) {
                MessageBox.alert("Invalid Information", "<br />Please correct the invalid fields<br />", null, null);
                return;
            }
            _form.submit(new Dictionary(
                "waitMsg", "Creating New Category",
                "reset", true,
                "params", new Dictionary("action", "InsertCategory"),
                "scope", this,
                "failure", new FormSubmitDelegate(delegate(Form form, Action action) {
                     MessageBox.alert("Error!", "There were errors saving this basket. <br />Please correct the errors and try again.", null, null);
                     fireEvent("inserted", this, false);
                }),
                "success", new FormSubmitDelegate(delegate(Form form, Action action) {
                    _dialog.hide(null);
                    fireEvent("inserted", this, true);
                })

            ));
        }
    }

    public class CategoryDetailsFormEvents {
        /// <summary>Fires when a new category is inserted
        /// <pre><code>
        /// USAGE: ({bool} success)
        /// </code></pre>
        /// <list type="bullet">
        /// <item><term><b>success</b></term><description>true, if the insert was successful</description></item>
        /// </list>
        /// </summary>
        public static string inserted { get { return "inserted"; } }
        /// <summary>Fires when a category is updated
        /// <pre><code>
        /// USAGE: ({bool} success, {Dictionary} newValues)
        /// </code></pre>
        /// <list type="bullet">
        /// <item><term><b>success</b></term><description>true, if the update was successful</description></item>
        /// <item><term><b>newValues</b></term><description>the new values entered into the form</description></item>
        /// </list>
        /// </summary>
        public static string updated { get { return "updated"; } }
    }

    public delegate void CategoryDetailsFormInsertedDelegate(CategoryDetailsForm form, bool success);
    public delegate void CategoryDetailsFormUpdatedDelegate(CategoryDetailsForm form, bool success, Dictionary values);
}
